import * as RongIMLib from '@rongcloud/imlib-v4'
import store from '@/store/index.js'
const imTool = {
	getMsgList: (im) => {
		im.Conversation.getList({
		  order: 0
		}).then(conversationList => {
		  console.log('获取会话列表成功', conversationList);
			store.dispatch('setMsgList', conversationList);
			// 删除会话，测试用
			// conversationList.map(item => {
				// const conversation = im.Conversation.get({
				//   targetId: '43',
				//   type: 3
				// });
				// conversation.destory().then(() => console.log('删除会话成功'));
			// })
		});
	},
	imMsgFn: (im, id, type, msgType, content, ) => {
		let userInfo = uni.getStorageSync('groupUserInfo')
		let sendType = type == 3 ? RongIMLib.CONVERSATION_TYPE.GROUP : RongIMLib.CONVERSATION_TYPE.PRIVATE
		const conversation = im.Conversation.get({
		  targetId: id,
		  type: sendType
		});
		console.log(userInfo)
		content.userInfo = userInfo
		return new Promise((reslove, reject) => {
			switch (msgType) {
				case 'text':
					conversation.send({
					  messageType: RongIMLib.MESSAGE_TYPE.TEXT, // 'RC:TxtMsg'
					  content: content
					}).then(function(message){
					  console.log('发送文字消息成功', message);
						reslove(message)
					}).catch(err => {
						console.log('发送文字消息失败', err)
						reject(err)
					});
					break;
				case 'getMsg':
					let option = {
					  timestamp: +new Date(),
					  count: 20
					};
					conversation.getMessages(option).then(function(result){
					  var list = result.list; // 历史消息列表
					  var hasMore = result.hasMore; // 是否还有历史消息可以获取
					  console.log('获取历史消息成功', list, hasMore);
						store.dispatch('setHasMore', hasMore)
						store.dispatch('setNowMsgList', list)
					});
					break;
				case 'del':
					// 删除会话
					conversation.destory().then(() => {
						console.log('删除会话成功')
						let list = store.state.msgList
						list.map((item, index) => {
							if (item.targetId == id) {
								list.slice(index, 1)
							}
						})
					});
					break;
			}
		})
	}
}

export default imTool